package cn.edu.tju.cas.rest.aspect;

import cn.edu.tju.cas.entity.UserEntity;
import cn.edu.tju.cas.util.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

/**
* Created by catold on 15/12/18.
*/
@Aspect
public class LoginAspect {

    @Autowired
    Config config;

    @Pointcut("execution(* cn.edu.tju.cas.rest.controller.*.*(..)) && !withoutAuthorization()")
    public void loginCheck() {

    }


    @Pointcut("execution(* cn.edu.tju.cas.rest.controller.UserController.login*(..)) ||" +
            "execution(* cn.edu.tju.cas.rest.controller.UserController.logout*(..))")
    public void withoutAuthorization() {

    }


    @Around("loginCheck()")
    public Object validateUser(ProceedingJoinPoint jp) throws Exception {
//        System.out.println("test" + SessionUtil.isLogin());
        if (!SessionUtil.isLogin() || !PassedTicket.getInstance().containTicket(SessionUtil.getTicket())) {
            // 未登录验证
            StateCode stateCode = StateCode.buildCode(BizCode.WITHOUT_AUTHORIZATION);
            stateCode.addData("loginUrl", config.getCasLoginUrl());
            SessionUtil.clear();

            return stateCode;
        }


        try {
            // 权限验证
            MethodSignature signature = (MethodSignature) jp.getSignature();
            Method method = signature.getMethod();
//            System.out.println(method.getAnnotationsByType(RequiredAdmin.class));
            if(!SessionUtil.isAdmin()){
                for (Annotation annotation: method.getDeclaredAnnotations()) {
                    if(annotation instanceof RequiredAdmin){
                        return StateCode.buildCode(BizCode.WRONGPERMISSION);
                    }
                }
            }

            return jp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return StateCode.buildCode(BizCode.FAIL);
        }
    }
}
